package com.hm.pan.controller;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hm.pan.annotation.CheckLogin;
import com.hm.pan.annotation.NoLogin;
import com.hm.pan.model.Message;
import com.hm.pan.model.ResultObj;
import com.hm.pan.model.User;
import com.hm.pan.service.MessageService;

@RestController
@RequestMapping("message")
@CheckLogin
public class MessageController {

	@Resource
	private MessageService messageServic;

	// 查找所有的用户反馈信息
	@RequestMapping("all")
	@NoLogin
	public Object findAll(Integer page) {
		System.out.println("++++++++++++++" + page);

		Integer tiao = messageServic.count();
		int yeshu = tiao % 5 == 0 ? tiao / 5 : tiao / 5 + 1;
		System.out.println("页数：" + yeshu);

		if (page != null) {
			List<Message> messages = messageServic.findByPage(page * 5);
			for (Message message : messages) {
				message.setYeshu(yeshu);
			}
			return new ResultObj(200, messages);
		}
		List<Message> messages = messageServic.findAll();
		return new ResultObj(200, messages);
	}

	// 插入用户的反馈信息
	@RequestMapping("insertMessage")
	public Object insertMessage(String messageContent, HttpSession session) {

//		System.out.println("++++++++++++++++++++" + messageContent);

		// 获取本地时间
		Timestamp messageTime = getTime();
		// 通过session获取当前用户的
		User user = (User) session.getAttribute("user");
		Long userId = user.getUserId();
		System.out.println(userId);

		Message message = new Message();
		message.setMessageContent(messageContent);
		message.setUserId(userId);
		message.setMessageTime(messageTime);

		Object insertMessage = messageServic.insertMessage(message);
		if (insertMessage != null) {
			return new ResultObj(200, insertMessage);
		} else {
			return new ResultObj(400, insertMessage);
		}
	}

	// 将本地时间设置日期格式，再转换为Timestamp类型
	public Timestamp getTime() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置本地日期格式
		Date date = new Date();
		String time = df.format(date);
		return Timestamp.valueOf(time); // 将String转为Timestamp类型
	}
}
